#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/6/22 16:07
# @Author : wn 
# @File: transfer.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡
import json
from operator import itemgetter

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View

from utils.service import my_page
from trade.models import *
import datetime
from trade.model_choices import *

from django.core import serializers
from trade.search_page import *
from utils.chardate import chardate
from trade.OperationLog import OperationLog


class TransferApplication(View):
    '''
    移交策略
    '''

    def get(self, request):
        # 当前登录用户
        username = request.GET.get('customerid', None)
        # 记录用户
        if username:
            request.session['customerid'] = username
        origuser = Strategy.objects.using('quantWebDB').values("customerid").distinct().all()
        customerid = Strategy.objects.using('quantWebDB').exclude(customerid=username).values("customerid").distinct().all()
        userobj = Strategy.objects.using('quantWebDB').exclude(stggroup="3").exclude(stgname=username).all()
        return render(request, "tranferapp.html",
                      {"orguser": origuser, "user": customerid, "userobj": userobj, "currentuser": username})

    def post(self, request):
        try:
            customerid = request.session.get('id', 'noCid')
            if request.POST.get('type') == "tran_app":
                oowner = request.POST.get("oowner")
                stgp = request.POST.get("stgp")
                stgidlist = json.loads(request.POST.get("stgidlist"))
                nowner = request.POST.get("nowner")
                for stgid in stgidlist:
                    stgname = list(Strategy.objects.using('quantWebDB').filter(stgid=int(stgid)).values_list("stgname").first())[0]
                    # 如果当前记录已经存在, 则不予申请
                    if Transfer.objects.using('quantWebDB').filter(ruleid=int(stgid), orignalowner=oowner,
                                               auditstatus="1").exists():
                        return HttpResponse("exist")
                    Transfer.objects.using('quantWebDB').create(
                        ruleid=int(stgid),
                        stgroup=stgp,
                        orignalowner=oowner,
                        newowner=nowner,
                        applydatetime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        stgname=stgname,
                        auditstatus='1',
                    )
                    # 记录操作日志
                    Log(customerid, oowner, nowner, stgname, stgid, "appl")

                trlist = search_trans("", "", "")
                json_trans = serializers.serialize("json", trlist)
                return JsonResponse(json_trans, safe=False)
            elif request.POST.get('type') == "search":
                oowner = request.POST.get("oowner")
                stgname = request.POST.get("stgname")
                status = request.POST.get("status")
                trlist = search_trans(oowner, stgname, status)

                json_trans = serializers.serialize("json", trlist)
                return JsonResponse(json_trans, safe=False)
        except Exception as e:
            print(e)
            return HttpResponse("error")


class TransferApproval(View):
    def get(self, request):
        # 当前登录用户
        username = request.GET.get('customerid', None)
        # 记录用户
        if username:
            request.session['customerid'] = username
        return render(request, "tranfercheck.html")

    def post(self, request):
        try:
            customerid = request.session.get("customerid")
            stgid = request.POST.get("stgid")
            preuser = request.POST.get("preuser")
            newuser = request.POST.get("newuser")
            if request.POST.get("type") == "approval":
                # 修改strategy表
                Strategy.objects.using('quantWebDB').filter(stgid=stgid).update(
                    customerid=newuser
                )

                # 修改channelrel(live)
                if Customerchannelrel.objects.using('quantLiveDB').filter(
                        customerid=stgid).exists():
                    Customerchannelrel.objects.using('quantLiveDB').filter(
                        customerid=stgid).update(apiinvestorid=newuser, )

                # 修改channelrel(paper)
                if Customerchannelrel.objects.using('quantPaperDB').filter(
                        customerid=stgid).exists():
                    Customerchannelrel.objects.using('quantPaperDB').filter(
                        customerid=stgid).update(apiinvestorid=newuser)

                # 修改transfer表
                Transfer.objects.using('quantWebDB').filter(ruleid=stgid).update(
                    auditstatus="3",
                    approvaldatetime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                )
                # 更新时间
                if Rule.objects.using('quantLiveDB').filter(ruleid=stgid).exists():
                    Rule.objects.using('quantLiveDB').filter(ruleid=stgid).update(
                        ruleversion=datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
                    )
                if Rule.objects.using('quantPaperDB').filter(ruleid=stgid).exists():
                    Rule.objects.using('quantPaperDB').filter(ruleid=stgid).update(
                        ruleversion=datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
                    )

                # 记录操作日志
                Log(customerid, preuser, newuser, "", stgid, "appro")
                trlist = search_trans("", "", "")
                json_trans = serializers.serialize("json", trlist)
                return JsonResponse(json_trans, safe=False)
            elif request.POST.get("type") == "confuse":
                # 更新transfer表
                Transfer.objects.using('quantWebDB').filter(ruleid=stgid).update(
                    auditstatus="2",
                    approvaldatetime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                )

                # 记录操作日志
                Log(customerid, preuser, newuser, "", stgid, "confuse")
                trlist = search_trans("", "", "")
                json_trans = serializers.serialize("json", trlist)
                return JsonResponse(json_trans, safe=False)
        except Exception as e:
            print(e)
            return HttpResponse("")


def Log(customerid, oowner, nowner, stgname, stgid, type):
    log_dict = {}
    if type == "appl":
        log_dict = {
            'customerid': customerid,
            'modular': '1',
            'optfunction': '11',
            'optinfo': '移交申请操作成功，策略ID：%s，策略名称：%s，原归属人：%s，移交至：%s' % (
                stgid, stgname, oowner, nowner),
            'opttime': chardate(),
        }
    elif type == "appro":
        log_dict = {
            'customerid': customerid,
            'modular': '1',
            'optfunction': '12',
            'optinfo': '审批操作成功，策略ID：%s，原归属人：%s，移交至：%s' % (
                stgid, oowner, nowner),
            'opttime': chardate(),
        }
    elif type == "confuse":
        log_dict = {
            'customerid': customerid,
            'modular': '1',
            'optfunction': '12',
            'optinfo': '驳回操作成功，策略ID：%s，原归属人：%s，移交至：%s' % (
                stgid, oowner, nowner),
            'opttime': chardate(),
        }
    OperationLog.opt_log(log_dict),
